package handler

import (
	db "echo_prj/db"
	"fmt"
	"io"
	"log"
	"os"
	"strconv"
	"time"

	"github.com/labstack/echo"
	/* "compress/gzip"
	"bytes"
	"io/ioutil" */)

//保存文件
func saveFile(c echo.Context) (filePath string, fileName string, err error) {
	uploadFile, err := c.FormFile("file")
	if err != nil {
		return
	}
	src, err := uploadFile.Open()
	if err != nil {
		return
	}
	defer src.Close()

	timeStamp := fmt.Sprint(time.Now().UnixNano())
	os.Mkdir("./view/static/file/img", 0777)
	saveFiles, err := os.OpenFile("./view/static/file/img/"+timeStamp+"-"+uploadFile.Filename, os.O_WRONLY|os.O_CREATE, 0666)
	filePath = "/static/file/img/" + timeStamp + "-" + uploadFile.Filename
	fileName = uploadFile.Filename
	if err != nil {
		return
	}
	io.Copy(saveFiles, src)

	defer saveFiles.Close()
	//同步到cdn
	err = SyncToCdn()
	if err != nil {
		return
	}
	return
}

//保存富文本中的图片
func saveTextImg(c echo.Context) (filePath string, fileName string, err error) {
	uploadFile, err := c.FormFile("file")
	if err != nil {
		return
	}
	src, err := uploadFile.Open()
	if err != nil {
		return
	}
	defer src.Close()

	timeStamp := fmt.Sprint(time.Now().UnixNano())
	os.Mkdir("./view/static/file/textImg", 0777)
	saveFiles, err := os.OpenFile("./view/static/file/textImg/"+timeStamp+"-"+uploadFile.Filename, os.O_WRONLY|os.O_CREATE, 0666)
	filePath = "/static/file/textImg/" + timeStamp + "-" + uploadFile.Filename
	fileName = uploadFile.Filename
	if err != nil {
		return
	}
	io.Copy(saveFiles, src)

	defer saveFiles.Close()
	//同步到cdn
	err = SyncToCdn()
	if err != nil {
		return
	}
	return
}

//上传图片
type imgRes struct {
	Id    int64  `json:"id"`
	Title string `json:"title"`
	Src   string `json:"src"`
}

func PostImg(c echo.Context) error {
	var a = Res{}

	filePath, fileName, err := saveFile(c)
	if err != nil {
		log.Println("PostImg,err=", err)
		a.Code = -1
		a.Msg = "参数错误"
		return c.JSON(200, a)
	}

	id, err := db.PostImg(filePath, fileName)
	if err != nil {
		log.Println("PostImg,err=", err)
		a.Code = -1
		a.Msg = err.Error()
	} else {
		a = Res{
			Code: 200,
			Msg:  "",
			Result: imgRes{
				Id:    id,
				Title: fileName,
				Src:   filePath,
			},
		}
	}
	return c.JSON(200, a)
}

func TextImg(c echo.Context) error {
	var a = Res{}
	filePath, fileName, err := saveTextImg(c)
	if err != nil {
		log.Println("TextImg,err=", err)
		a.Code = -1
		a.Msg = "参数错误"
		return c.JSON(200, a)
	}

	id, err := db.TextImg(filePath, fileName)
	if err != nil {
		log.Println("TextImg,err=", err)
		a.Code = -1
		a.Msg = err.Error()
	} else {
		a = Res{
			Code: 200,
			Msg:  "",
			Result: imgRes{
				Id:    id,
				Title: fileName,
				Src:   filePath,
			},
		}
	}
	return c.JSON(200, a)
}

//上传Banner
func PostBanner(c echo.Context) error {
	var a = Res{}
	filePath, fileName, err := saveFile(c)
	uid, err2 := strconv.Atoi(c.FormValue("id"))
	if err != nil || err2 != nil {
		log.Println("PostBanner,err=", err)
		a.Code = -1
		a.Msg = "参数错误"
		return c.JSON(200, a)
	}
	id, err := db.PostBanner(fmt.Sprint(uid), filePath, fileName)
	if err != nil {
		log.Println("PostBanner,err=", err)
		a.Code = -1
		a.Msg = err.Error()
	} else {
		a = Res{
			Code: 200,
			Msg:  "",
			Result: imgRes{
				Id:    id,
				Title: fileName,
				Src:   filePath,
			},
		}
	}
	return c.JSON(200, a)
}

//更新banner对应的prodId
func PostBannerProd(c echo.Context) error {
	var a = Res{}

	idStr := c.FormValue("formStr")
	id, err := db.PostBannerProd(idStr)
	if err != nil {
		log.Println("PostBannerProd,err=", err)
		a.Code = -1
		a.Msg = err.Error()
	} else {
		a = Res{
			Code:   200,
			Msg:    "",
			Result: id,
		}
	}
	return c.JSON(200, a)
}

//获取banner
func GetBanner(c echo.Context) error {
	var a = Res{}
	as, err := db.GetBanner()
	if err != nil {
		log.Println("GetBanner,err=", err)
		a.Code = -1
		a.Msg = err.Error()
	} else {
		a = Res{
			Code:   200,
			Msg:    "",
			Result: as,
		}
	}
	return c.JSON(200, a)
}

//删除无引用图片
func DelUselessImg() {
	log.Println(time.Now().Format("2006-01-02 15:04:05----") + "开始定时清理...")
	paths, err := db.DelUselessImg()
	if err != nil {
		log.Println("定时清理失败,err=", err)
		return
	}
	if len(paths) == 0 {
		log.Println("无需清理")
	} else {
		for _, v := range paths {
			//删除图片
			err := os.Remove(v)
			if err != nil {
				log.Println("DelUselessImg,err=", err)
				return
			}
		}
		log.Println(fmt.Sprintf(time.Now().Format("2006-01-02 15:04:05----")+"定时清理结束,清理图片%d张", len(paths)))
	}

}

/* func GizImg(w http.ResponseWriter, r *http.Request){
	w.Header().Add("Content-Encoding","gzip")
	w.Header().Add("Accept-Ranges","bytes")
	datasSlice, _ := ioutil.ReadFile("./view" + r.URL.Path )
	var b bytes.Buffer
	e,err := gzip.NewWriterLevel(&b,5)
	if err!= nil{
		return
	}
	defer e.Close()

	e.Write(datasSlice)
	e.Flush()
	//fmt.Println("gzip size:", len(b.Bytes()))

	bs := b.Bytes()
	w.Write(bs)
} */
